package com.atguigu.tingshu.order.startegy.impl;
import java.util.Date;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.model.order.OrderDerate;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.order.service.OrderDerateService;
import com.atguigu.tingshu.order.service.OrderDetailService;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.google.common.collect.Maps;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.order.OrderInfo;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.order.startegy.SaveOrderStrategy;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class WeiXinSaveOrderStrategy implements SaveOrderStrategy {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private OrderDerateService orderDerateService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private RedissonClient redissonClient;

    @Transactional
    @Override
    public OrderInfoVo saveOrder(OrderInfoVo orderInfoVo) {

        saveOrderAndDetailAndOrderDerate(orderInfoVo,orderInfoService,orderDetailService,orderDerateService);
        seadDelayTask(orderInfoVo.getTradeNo());
        return orderInfoVo;
    }

    //发布延迟任务
    private void seadDelayTask(String tradeNo) {
        RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue(RedisConstant.DELAY_QUEUE_ORDER_CANCEL);
        RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingQueue);
        delayedQueue.offer(tradeNo, RedisConstant.DELAY_TIME, TimeUnit.SECONDS);
    }



    @Override
    public String getPayWay() {
        return SystemConstant.ORDER_PAY_WAY_WEIXIN;
    }

    @Override
    public void saveOrderProcess(String orderNo) {//发布延迟任务
        seadDelayTask(orderNo);
    }
}
